/*
 * Copyright (C) 2004, Velocityme Partnership
 * VelocitymeWebClientService.java
 *
 * Created on 28 June 2004, 22:55
 */

package com.velocityme.www.interfaces;

//web imports
import com.velocityme.www.dto.*;
import com.velocityme.www.actionforms.*;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.*;

import org.apache.commons.beanutils.*;
//ejb interfaces
import com.velocityme.interfaces.*;
import com.velocityme.session.*;
import com.velocityme.valueobjects.*;


/**
 *
 * @author  bradloff
 */
public class VelocitymeLoginAction extends org.apache.struts.action.Action{
    
    /** Creates a new instance of VelocitymeWebClientService */
    public VelocitymeLoginAction() {
    }
    
    public ActionForward execute(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        LoginActionForm loginActionForm = (LoginActionForm)form;
        HttpSession session = request.getSession();
        KeySession key = KeySessionUtil.getHome().create();
        ActionErrors errors = new ActionErrors();
        switch(key.login(loginActionForm.getUsername(),
                         loginActionForm.getPassword(),
                         this.getClass().getPackage().getImplementationVersion(),
                         request.getRemoteHost())) {
            case KeySessionBean.LOGIN_SUCCESS:
                // now set up the required attributes
                session.setAttribute("sessionKey", key);
                session.removeAttribute("markedNodePK");
                NodePK nodePK = (NodePK)session.getAttribute("nodePK");
                if (nodePK == null)
                    return mapping.findForward("ACTION_HOME");
                else {
                    request.setAttribute("nodePK", nodePK);
                    return mapping.findForward("ACTION_NODE");
                }
            case KeySessionBean.LOGIN_LICENCE:
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.no.available.licence"));
                break;
            case KeySessionBean.LOGIN_PASSWORD:
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.incorrect.password"));
                break;
            case KeySessionBean.LOGIN_INVALID:
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.invalid.username"));
                break;
            default:
            case KeySessionBean.LOGIN_ERROR:
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.error"));
                break;
        }
        session.removeAttribute("sessionKey");
        saveErrors(request, errors);
        return mapping.findForward("ACTION_FAILED");
    }

    
}
